package com.keydom.ropeskipping;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.clj.fastble.BleManager;
import com.google.gson.Gson;
import com.keydom.ropeskipping.dot.CardHomeworkResultDTO;
import com.keydom.ropeskipping.dot.StudentHomeworkDTO;
import com.keydom.ropeskipping.service.SkipWorkServiceImpl;
import com.keydom.ropeskipping.utils.BluetoothListenerReceiver;
import com.keydom.ropeskipping.view.NonSwipeableViewPager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends FragmentActivity {
    private NonSwipeableViewPager viewPager;
    private ArrayList<Fragment> fragments;
    private ViewPagerAdapter viewpagerAdapter;

    private View topView1;
    private View topView2;
    private TextView topText1;
    private TextView topText2;

    private String imei;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                getList();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(0x80000000);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        AppApplication.getInstance().addActivity(this);

        BleManager.getInstance().enableBluetooth();
        initView();
        initEvent();
    }

    @SuppressLint({"MissingPermission", "HardwareIds"})
    private void initView() {
        viewPager = findViewById(R.id.viewPager);
        topView1 = findViewById(R.id.top_view1);
        topView2 = findViewById(R.id.top_view2);
        topText1 = findViewById(R.id.top_text1);
        topText2 = findViewById(R.id.top_text2);

        fragments = new ArrayList<>();
        fragments.add(new FirstFragment());
        fragments.add(new SecondFragment());
        viewpagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(viewpagerAdapter);

        TelephonyManager tManager = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
        imei = tManager.getDeviceId();

        handler.sendEmptyMessageDelayed(0, 1000);
    }

    private void initEvent() {
        topText1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getList();
                topView2.setVisibility(View.GONE);
                topView1.setVisibility(View.VISIBLE);
                viewPager.setCurrentItem(0);
            }
        });

        topText2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getList();
                topView1.setVisibility(View.GONE);
                topView2.setVisibility(View.VISIBLE);
                viewPager.setCurrentItem(1);
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction("REFRESH_LIST");
        filter.addAction("CLICK_KEYCODE_POWER");
        registerReceiver(mBroadcastReceiver, filter);
    }

    private void getList() {
        Log.e("TAG", "getList: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                final CardHomeworkResultDTO cardHomeworkResultDTO;
                try {
                    cardHomeworkResultDTO = SkipWorkServiceImpl.querySkipHomeworkById(imei);
                    if (new Gson().toJson(cardHomeworkResultDTO).equals(AppApplication.getInstance().listData)) {
                        //数据相等时，不去刷新列表
                        Log.d("MainActivity", "数据相等，不刷新列表");
                        return;
                    }
                } catch (Exception e) {
                    return;
                }
                AppApplication.getInstance().listData = new Gson().toJson(cardHomeworkResultDTO);
                List<ParcelUuid> uuids = new ArrayList<>();
                try {
                    for (int i = 0; i < cardHomeworkResultDTO.getExpands().length(); i++) {
                        JSONObject jsonObject = cardHomeworkResultDTO.getExpands().getJSONObject(i);
                        uuids.add(new ParcelUuid(UUID.fromString(jsonObject.getString("value"))));
                    }
                    AppApplication.getInstance().setBluetoothUuid(uuids);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final List<StudentHomeworkDTO> unfinishedList = new ArrayList<>();
                final List<StudentHomeworkDTO> completedList = new ArrayList<>();
                assert cardHomeworkResultDTO != null;
                if (cardHomeworkResultDTO != null && cardHomeworkResultDTO.getHomeworkList() != null && cardHomeworkResultDTO.getHomeworkList().size() > 0) {
                    for (StudentHomeworkDTO studentHomeworkDTO : cardHomeworkResultDTO.getHomeworkList()) {
                        if (studentHomeworkDTO.getStatus() == 0) {
                            unfinishedList.add(studentHomeworkDTO);
                        } else {
                            completedList.add(studentHomeworkDTO);
                        }
                    }
                }
                try {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                AppApplication.getInstance().historyUrl = cardHomeworkResultDTO.getHistoryRedirectUrl();
                                ((FirstFragment) fragments.get(0)).setStudentHomeworkDTOS(unfinishedList);
                                ((SecondFragment) fragments.get(1)).setStudentHomeworkDTOS(completedList);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        handler.removeMessages(0);
        BleManager.getInstance().disableBluetooth();
        BleManager.getInstance().destroy();
        AppApplication.getInstance().listData = null;
        unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            onDestroy();
            AppApplication.getInstance().exit();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    public static class ViewPagerAdapter extends FragmentPagerAdapter {
        private final ArrayList<Fragment> fragments;

        ViewPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("REFRESH_LIST".equals(action)) {
                getList();
                if (intent.hasExtra("page")) {
                    int page = intent.getIntExtra("page", 0);
                    if (page == 1) {
                        topText2.performClick();
                    } else {
                        topText1.performClick();
                    }
                }
            } else if ("CLICK_KEYCODE_POWER".equals(action)) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onDestroy();
                        AppApplication.getInstance().exit();
                    }
                }, 2000);
            }
        }
    };
}
